<template>
  <div>
    <el-tooltip :open-delay="1000" popper-class="tootipdiv" class="item" :disabled="Array.isArray(rowData[scriptItem.valueFields])&&rowData[scriptItem.valueFields].length===0||!rowData[scriptItem.valueFields]" effect="dark" placement="top">
      <div class="tootipdv" slot="content" style="max-height:300px;overflow:auto" v-html="tootipHander(rowData[scriptItem.valueFields],rowData.options,allValueList[rowData[scriptItem.keyFields]])"></div>
      <div style="float: left"
        :style="{ width: scriptItem.valueFieldsWidth }">
      <div v-if="(filterType==='boolean'||filterType==='booleanFlag')"
          style="width: 100%;">
        <el-select v-model="rowData[scriptItem.valueFields]"
                  clearable
                  style="width: 100%"
                  :disabled="isNotValue(rowData)">
          <el-option :label="'True'"
                    :value="true"></el-option>
          <el-option :label="'False'"
                    :value="false"></el-option>
        </el-select>
      </div>
      <div v-else-if="(filterType==='text' || filterType==='user' || filterType==='simpleText')"
          style="width: 100%">
        <template>
          <el-select v-model="rowData[scriptItem.valueFields]"
                     ref="fuzzySearch"
                     :multiple="rowData[scriptItem.optionFields]&&(rowData[scriptItem.optionFields].toLowerCase()==='in'||rowData[scriptItem.optionFields].toLowerCase()==='or'||rowData[scriptItem.optionFields].toLowerCase()==='not in')"
                    :remote="(nextTicketType==='jira'&&isRemoteObject[rowData[scriptItem.keyFields]]&&isRemoteObject[rowData[scriptItem.keyFields]]===100)||nextTicketType!=='jira'"
                    clearable
                    :disabled="isNotValue(rowData)"
                    reserve-keyword
                    :remote-method="remoteMethod"
                    @focus="setTempField(rowData[scriptItem.keyFields])"
                    @blur="clearTempField"
                    size="small"
                    collapse-tags
                    filterable style="width: 100%"
                    default-first-option
                    automatic-dropdown
                    :allow-create="allowCreate(rowData)">
            <el-option v-for="(fieldItem,fieldIndex) in allValueList[rowData[scriptItem.keyFields]]"
                      :key="fieldIndex"
                      :label="fieldItem.name"
                      :value="fieldItem.id">
                      </el-option>
          </el-select>
        </template>
      </div>
      <div v-else-if="filterType==='number'"
          style="width: 100%;">
        <template>
            <el-select v-model="rowData[scriptItem.valueFields]" 
                       ref="fuzzySearch"
                       :multiple="rowData[scriptItem.optionFields]&&(rowData[scriptItem.optionFields].toLowerCase()==='in'||rowData[scriptItem.optionFields].toLowerCase()==='or'||rowData[scriptItem.optionFields].toLowerCase()==='not in')"
                      clearable
                      :remote="(nextTicketType==='jira'&&isRemoteObject[rowData[scriptItem.keyFields]]&&isRemoteObject[rowData[scriptItem.keyFields]]===100)||nextTicketType!=='jira'"
                      :disabled="isNotValue(rowData)"
                      reserve-keyword
                      :remote-method="remoteMethod"
                      @focus="setTempField(rowData[scriptItem.keyFields])"
                      @blur="clearTempField"
                      size="small"
                      collapse-tags
                      filterable style="width: 100%"
                      @change="checkboxGroupChange"
                      default-first-option
                      :allow-create="allowCreate(rowData)">
              <template v-if="rowData[scriptItem.optionFields] === 'in' || rowData[scriptItem.optionFields] === 'not in'">
                <el-checkbox-group v-model="rowData[scriptItem.valueFields]" @change="checkboxGroupChange">
                  <el-option v-for="(fieldItem,fieldIndex) in allValueList[rowData[scriptItem.keyFields]]"
                            :key="fieldIndex"
                            :label="fieldItem.name"
                            :value="fieldItem.id">
                            </el-option>
                </el-checkbox-group>
              </template>
              <template v-else>
                <el-option v-for="(fieldItem,fieldIndex) in allValueList[rowData[scriptItem.keyFields]]"
                      :key="fieldIndex"
                      :label="fieldItem.name"
                      :value="fieldItem.id">
                      </el-option>
              </template>

            </el-select>
        </template>
      </div>
      <div v-else-if="(filterType==='datetime'||filterType==='date')"
          style="width: 100%;">
        <el-popover v-model="datetimeStatus"
                    ref="datetime-popover"
                    :disabled="isNotValue(rowData)"
                    >
          <el-input style="width: 100%;"
                    slot="reference" clearable
                    v-model="rowData[scriptItem.valueFields]"
                    :placeholder="scriptItem.valueHint"
                    :disabled="isNotValue(rowData)"
                    readonly></el-input>
          <el-tabs v-if="optValue === 'timeofday'" v-model='timeTabs'>
            <el-tab-pane label="Time"
                        name="Time">
              <el-time-picker
                is-range
                v-model="timeOfDayValStart"
                range-separator="-"
                format="HH:mm"
                :disabled="isNotValue(rowData)"
                value-format="HH:mm"
                start-placeholder="Start time"
                end-placeholder="End time"
                placeholder="">
              </el-time-picker>
            </el-tab-pane>
          </el-tabs>
          <el-tabs v-model='datetimeTabs' v-else>          
          <el-tab-pane label="Time"
                      v-if="optValue !== 'in'"
                      name="time">
            <el-date-picker v-model="datePickerValue" :disabled="isNotValue(rowData)"
                            :type="rowData.type === 'date'?'date':'datetime'"
                            :value-format="rowData.type === 'date'?'yyyy-MM-dd':'yyyy-MM-dd HH:mm:ss'">
            </el-date-picker>
          </el-tab-pane>

          </el-tabs>
          <el-row style="margin-top: 10px">
            <el-col :span="24"
                    style="text-align:right;">
              <el-button size="mini"
                        @click="clearDatetime">Clear</el-button>
              <el-button type="primary"
                        size="mini"
                        @click="saveDatetime()">Save</el-button>
            </el-col>
          </el-row>
        </el-popover>
      </div>
      <div v-else>
        <el-input :style="{ width: scriptItem.valueFieldsWidth }"
                  v-model="inputValue" clearable
                  :placeholder="scriptItem.valueHint"
                  :disabled="isNotValue(rowData)"></el-input>
      </div>
      </div>
    </el-tooltip>
  </div>
</template>

<script>
import mixinTypeViewModule from '@/mixins/script-type-view-module'
import { debounce } from 'lodash'
export default {
  mixins: [mixinTypeViewModule],
  props: {
    rowIndex: {
      type: String,
      default: null
    },
    filterType: {
      type: String,
      default: null
    },
    allValueList: {
      type: Object,
      default: () => { }
    },
    nextTicketType: {
      type: String,
      default: null
    },
    isRemoteObject: {
      type: Object,
      default: ()=>{}
    },
    gadgetSetting: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data () {
    return {
      autoTaskCheckGpModel: [],
      autoTaskChecked: false,
      checked: false,
      timeOfDayValStart: ['00:00', '23:59'],
      datetimeStatus: false,
      datetimeTabs: 'variate', // variate time
      timeTabs: 'Time',
      number: -1,
      isInclude: 'unincludes', // includes unincludes
      dateType: '',
      dateMoreList: '',
      dateMore: '',
      datePickerValue: null,
      rowData: {},
      inputValue: '',
      thisIndex: -1,
      parentIndex: -1,
      indexStr: '',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [{
          text: 'Nowadays',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: 'Yesterday',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: 'A week ago',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      dateEquals: ''
    }
  },
  watch: {
    allValueList (val) {
      this.checkIsSelectAll()
    },
    datetimeStatus: {
      handler: function (val) {
        if (val) {
          if ((this.rowData.value && this.rowData.value.search(/\{/) > -1) || this.optValue === 'in') {
            this.datetimeTabs = 'variate'
          } else {
            this.datetimeTabs = 'time'
          }
          document.addEventListener('mousedown', this.mouseDownListener)
        } else {
          document.removeEventListener('mousedown', this.mouseDownListener)
        }
      },
      immediate: true
    },
    rowIndex: {
      handler: function (newData) {
        this.indexStr = newData
        if (newData.indexOf('_') !== -1) {
          this.thisIndex = parseInt(newData.split('_')[0])
          this.parentIndex = parseInt(newData.split('_')[1])
        } else {
          this.thisIndex = parseInt(newData)
        }
      },
      deep: true,
      immediate: true
    },
    dataFormSub: {
      handler: function (val) {
        if (this.indexStr.indexOf('_') !== -1) {
          this.rowData = val[this.parentIndex][this.scriptItem.dataArr][this.thisIndex]
        } else {
          this.rowData = val[this.thisIndex]
        }
        this.checkedConditionExistence()
        if (this.rowData.opt === 'timeofday' && this.rowData.value) {
          this.timeOfDayValStart[0] = this.rowData.value.replace('{', '').replace('}', '').split('~')[0].substring(0, 5)
          this.timeOfDayValStart[1] = this.rowData.value.replace('{', '').replace('}', '').split('~')[1].substring(0, 5)
        }
        if (this.rowData.value) {
          let strValue = this.rowData.value
          if (typeof strValue === 'string' && strValue.search(/\{/) > -1 && strValue.search(/\}/) > -1) {
            let expression = strValue.slice(strValue.search(/\{/) + 1, strValue.search(/\}/))
            let tempList = expression.split(/\//)
            this.dateMore = tempList[0]
            if (tempList[0] === 'last' || tempList[0] === 'next' || tempList[0] === 'current' || tempList[0] === 'previous') {
              this.dateMoreList = [tempList[0]]
            } else {
              this.dateMoreList = ['weeks', tempList[0]]
            }
            this.number = isNaN(Number(tempList[1])) ? 1 : tempList[1]
            this.dateType = tempList[2]
            this.dateEquals = tempList[0]
            tempList.length > 3 && (this.isInclude = tempList[3])
            this.datetimeTabs = 'variate'
          } else {
            this.datePickerValue = strValue
            this.datetimeTabs = 'time'
          }
        }
      },
      immediate: true,
      deep: true
    },
  },
  computed: {
    rowDataVal () {
      return this.rowData.value
    },
    serviceBoardVal () {
      return this.dataForm[this.scriptItem.text][this.scriptItem.dataArr][0]
    },
    dataFormSub () {
      return this.dataForm[this.scriptItem.text][this.scriptItem.dataArr]
    },
    datetimeVariateMore () {
      let temp = []
      try {
        temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'filter_variate_more').dataList
      } catch (error) { }
      return temp
    },
    datetimeVariateType () {
      let temp = []
      try {
        temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'filter_variate_type').dataList
      } catch (error) { }
      return temp
    },
    optValue () {
      try {
        return this.rowData[this.scriptItem.optionFields]
      } catch (error) {
        return ''
      }
    },
    dateWeekEquals () {
      let temp = []
      try {
        temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'filter_week_of_day').dataList
      } catch (error) { }
      return temp
    },
    datetimeVariateMoreTreeList () {
      let temp = []
      try {
        this.datetimeVariateMore.map(e => {
          temp.push({
            label: e.dictLabel,
            value: e.dictValue
          })
        })
        let weeks = {
          label: 'Weeks',
          value: 'weeks',
          children: []
        }
        this.dateWeekEquals.map(e => {
          weeks.children.push({
            label: e.dictLabel,
            value: e.dictValue
          })
        })
        temp.push(weeks)
      } catch (error) { }
      return temp
    },
    datetimeVariateMoreTreeListNormal () {
      let temp = []
      try {
        this.datetimeVariateMore.map(e => {
          temp.push({
            label: e.dictLabel,
            value: e.dictValue
          })
        })
      } catch (error) { }
      return temp
    }
  },
  methods: {
    isNotValue(rowData) {
      let res = this.gadgetSetting.customRuleOptionList.filter(ii=>ii.type === rowData.type).find(i=>i.value === rowData.opt)
      if(res) {
        return res.notValue
      }
    },
    allowCreate(rowData) {
      try {
        let res = this.gadgetSetting.customRuleKeyArray.find(i=>i.value === rowData.key)
        if(res) {
          return !res.url
        }
      } catch (error) {
        
      }
    },
    checkedConditionExistence () {
      if (this.rowData.currOption && this.rowData.options.length > 0) {
        if (!this.rowData.options.find(e => e.id === this.rowData.currOption.id)) {
          this.rowData.options.push(this.rowData.currOption)
        }
      }
    },
    tootipHander (arr, selectRow, rowData) {
      try {
        var labelFields = null
        var selectRowList = rowData
        if (Array.isArray(arr)) {
          labelFields = selectRowList ? this.selectTooltipViewArr(arr, selectRowList) : arr
        } else {
          labelFields = selectRowList ? this.selectTooltipViewStr(arr, selectRowList) : arr
        }
      } catch (error) {

      }
      var str = ''
      if (Array.isArray(labelFields)) {
        labelFields.forEach((i,index) => {
          if (i === undefined) {
            str += arr[index] + '&nbsp;&nbsp;&nbsp;&nbsp;' + '<br>'
          } else {
            str += i + '&nbsp;&nbsp;&nbsp;&nbsp;' + '<br>'
          }        
        })
        return str
      } else {
        return String(labelFields) + '&nbsp;&nbsp;&nbsp;&nbsp;' || String(arr) +'&nbsp;&nbsp;&nbsp;&nbsp;'
      }
    },
    selectTooltipViewArr (arr, selectRowList) {
      let labelFields = null
      labelFields = arr.map(item => {
        let res1 = selectRowList.find(i => i.id === item)
        if (res1) {
          return res1.name
        } else {
          return res1
        }
      })
      return labelFields
    },
    selectTooltipViewStr (arr, selectRowList) {
      var labelFields = null
      labelFields = selectRowList.find(i => i.id === arr)
      if (labelFields) {
        return labelFields.name
      } else {
        return labelFields
      }
    },
    checkIsSelectAll () {
      if (this.filterType === 'number') {
        if (this.rowData[this.scriptItem.valueFields].length === this.allValueList[this.rowData[this.scriptItem.keyFields]].length) this.checked = true
        else this.checked = false
      }
    },
    selectAll (e) {
      if (e) this.rowData[this.scriptItem.valueFields] = this.allValueList[this.rowData[this.scriptItem.keyFields]]
      else this.rowData[this.scriptItem.valueFields] = []
      if(this.allValueList[this.rowData[this.scriptItem.keyFields]][0].id) {
        this.rowData[this.scriptItem.valueFields] = this.allValueList[this.rowData[this.scriptItem.keyFields]].map(i=>i.id)
      }
    },
    autoTaskSelectAll (e) {
      if (e) {
        let arrValue = []
        let arrLabel = []
        this.scriptItem.autoTaskStatuOptionList.forEach(element => {
          arrValue.push(element.value)
          arrLabel.push(element.label)
        })
        this.autoTaskCheckGpModel = arrLabel
        this.rowData[this.scriptItem.valueFields] = arrValue
      } else {
        this.rowData[this.scriptItem.valueFields] = []
        this.autoTaskCheckGpModel = []
      }
    },
    checkboxGroupChange (val) {
      if (this.rowData[this.scriptItem.optionFields] === 'in' || this.rowData[this.scriptItem.optionFields] === 'not in') {
        if (val.length === this.allValueList[this.rowData[this.scriptItem.keyFields]].length) this.checked = true
        else this.checked = false
      }
    },
    autoTaskCheckboxGroupChange (e) {
      if (this.rowData[this.scriptItem.optionFields] === 'in' || this.rowData[this.scriptItem.optionFields] === 'not in') {
        if (this.rowData[this.scriptItem.valueFields].length === this.scriptItem.autoTaskStatuOptionList.length) {
          this.autoTaskChecked = true
          let arrLabel = []
          this.scriptItem.autoTaskStatuOptionList.forEach(element => {
            arrLabel.push(element.label)
          })
          this.autoTaskCheckGpModel = arrLabel
        } else {
          this.autoTaskChecked = false
          let arrLabel = []
          this.scriptItem.autoTaskStatuOptionList.forEach(element => {
            if (e.includes(element.value))arrLabel.push(element.label)
          })
          this.autoTaskCheckGpModel = arrLabel
        }
      } else {
        // this.rowData[this.scriptItem.valueFields] = ''
      }
    },
    getTerritory () {
      this.$interface.apiManager.getLocationSelectListApi().then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.rowData.options = res.data
        this.$forceUpdate()
      })
    },
    saveDatetime () {
      let temp = ''
      if (this.optValue === 'timeofday') {
        if (this.timeOfDayValStart) this.rowData.value = `{${this.timeOfDayValStart[0]}:00~${this.timeOfDayValStart[1]}:59}`
        this.datetimeStatus = false
        return false
      }
      if (this.datetimeTabs === 'variate') {
        if (this.dateMore === 'current') {
          if (!this.dateType) { return this.$message.error('Please select unit.') }
          this.number = 0
          temp = `{${this.dateMore}/${this.number}/${this.dateType}/${this.filterType}}`
        } else if (this.dateMore === 'previous') {
          if (!this.dateType) { return this.$message.error('Please select unit.') }
          temp = `{${this.dateMore}/${this.number}/${this.dateType}/${this.filterType}}`
        } else {
          if (this.dateMoreList[0] === 'weeks') {
            temp = `{${this.dateMore}/${this.filterType}}`
          } else {
            if (!this.dateType) { return this.$message.error('Please select unit.') }
            temp = `{${this.dateMore}/${this.number}/${this.dateType}/${this.isInclude}/${this.filterType}}`
          }
        }
      } else if (this.datetimeTabs === 'time') {
        temp = this.datePickerValue
      }
      this.rowData.value = temp
      this.datetimeStatus = false
    },
    clearDatetime () {
      this.rowData.value = ''
      this.dateEquals = ''
      this.timeOfDayValStart = null
    },
    dateTypeFormat (dateType) {
      if (dateType) {
        let temp = []
        temp = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'filter_variate_type').dataList
        return temp.find(e => e.dictValue === dateType).subjectCode
      }
      return ''
    },
    mouseDownListener (event) {
      if (!event.target.closest('.block-model-dialog')) {

      } else {
        this.datetimeStatus = false
      }
    },
    remoteMethod (e) {
      this.$emit('changeValue', e, localStorage.getItem('tempFilterValue'))
    },
    setTempField (field) {
      localStorage.setItem('tempFilterValue', field)
        this.$refs.fuzzySearch.$refs.input.blur = () => {
          this.$emit('changeValue', '', localStorage.getItem('tempFilterValue'))
        };
    },
    clearTempField () {
      localStorage.removeItem('tempFilterValue')
    },
  }
}
</script>

<style scoped>
.more {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.tootipdv::-webkit-scrollbar{
  width:5px;
  height:5px;
  border-radius:5px;
}
.tootipdv::-webkit-scrollbar-track{
  background: #303133;
  border-radius:5px;
}
.tootipdv::-webkit-scrollbar-thumb{
  background: #888;
  border-radius:5px;
}
.tootipdv::-webkit-scrollbar-thumb:hover{
  background: #888;
  border-radius:5px;
}
.tootipdv::-webkit-scrollbar-track-piece {
  background: #303133;
  border-radius:5px;
}
</style>
<style>
.tootipdiv.el-tooltip__popper {
  padding-right: 0;
}
</style>
